package io;

import org.junit.Test;

import java.io.*;

/**
 * Created by :Infaraway
 * DATE : 2017/3/4
 * Time : 10:57
 * Funtion :
 */
public class FileTest {


    /**
     * 利用缓冲流读写文件内容
     * @throws IOException
     */
    @Test
    public void testBuffer() throws IOException {
        //创建输入输出缓冲流对象
        Reader in = new FileReader("file\\io.txt");
        BufferedReader bufferedReader = new BufferedReader(in);

        Writer out = new FileWriter("file\\io2.txt");
        BufferedWriter bufferedWriter = new BufferedWriter(out);

        String strLine;
        while ((strLine = bufferedReader.readLine()) != null){
            //写入文件
            bufferedWriter.write(strLine);
            //换行
            bufferedWriter.newLine();
            //写入到文件
            bufferedWriter.flush();
            System.out.println(strLine);
        }

        //直接关包装流即可
        bufferedReader.close();
        bufferedWriter.close();
    }

    /**
     * 测试字符输入流
     * @throws IOException
     */
    @Test
    public void testReader() throws IOException {

        Reader reader = new FileReader("file\\io.txt");

        char [] buffer = new char[10];
        int len = 0;
        while ((len = reader.read(buffer)) != -1){
            for (int i = 0; i < len; i++) {
                System.out.print(buffer[i]);
            }
        }
    }


    /**
     * 测试字节输入流
     * @throws IOException
     */
    @Test
    public void testInputStream() throws IOException {
        //创建字节输入流
        InputStream in = new FileInputStream("io.txt");
        //读取文件内容
       /* //1)一次读取一个字节
        int result = in.read();
        while (result != -1){
            System.out.print((char)result);
            result = in.read();
        }
        System.out.print((char)result);*/

        //2)一次读取一个字节数组
        byte [] bufferBytpe = new byte[1024];
        int len = 0;
        while ((len = in.read(bufferBytpe)) != -1){
            for (int i = 0; i < len; i++) {
                System.out.print((char)bufferBytpe[i]);
            }
        }
        //关闭流资源
        in.close();
    }

}
